
package com.ifcar.app.activity.news;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import com.ifcar.app.activity.MyApplication;
import com.ifcar.app.activity.HomePage;
import com.ifcar.app.activity.SearchNewsActivity;
import com.ifcar.app.fragment.FragmentUtil;
import com.ifcar.app.fragment.NRFragment;
import com.ifcar.app.fragment.NRTabFragment;
import com.ifcar.app.fragment.NRTabFragment.TabManager.TabInfo;
import com.ifcar.app.model.NewsColumn;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.view.MyTabWidget;
import com.ifcar.app.view.ScrollTabs;
import com.ifcar.app.activity.R;

public class NewsTabFragment extends NRTabFragment {
	
	private static final String MORE_TAB_TAG = "more";

    private final List<Map<String, Object>> mColumnsList = new ArrayList<Map<String, Object>>();
    
    private LoadingListView mLoadingListView;

    private String mLastTab;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setNRMenu(R.layout.news_main_menu, new int[] {
                R.id.menu_download_article, R.id.menu_theme_change, R.id.menu_news_search,
                R.id.menu_my_comment, R.id.menu_my_collect, R.id.menu_make_column,
                R.id.menu_setting, R.id.menu_exit
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news_layout, container, false);
    }

    @Override
    public int getContainerId() {
        return R.id.realtabcontent;
    }

    @Override
    public void onViewCreatedNR(View view, Bundle savedInstanceState) {
        super.onViewCreatedNR(view, savedInstanceState);
        ScrollTabs scrollTabs = (ScrollTabs) view.findViewById(R.id.scroll_tabs);
        scrollTabs.setLeftView(view.findViewById(R.id.column_to_left));
        scrollTabs.setRightView(view.findViewById(R.id.column_to_right));
        
        mLoadingListView = (LoadingListView) view.findViewById(R.id.news_loading_list);

        LayoutInflater inflate = LayoutInflater.from(getActivity());
		View moreView = inflate.inflate(R.layout.more_layout,
				mLoadingListView.getListView(), false);
        mLoadingListView.setLoadingMoreView(moreView, R.id.show_more_button);
    }

    @Override
    public void onResume() {
        super.onResume();

        MyApplication app = getApplication();
        if (app.getIsCustomColumnFinish()) {
            app.setIsCustomColumnFinish(false);
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            MyTabWidget tabWidget = (MyTabWidget) getTabHost().getTabWidget();
            tabWidget.setEditMode(true);
            updateTab(getTabManager(), getTabHost(), inflater);
            getTabHost().setCurrentTabByTag(MORE_TAB_TAG);
            tabWidget.setEditMode(false);
        }
    }
    
    @Override
    public void onTabSelected(boolean first) {
    
        super.onTabSelected(first);
    }
    
    @Override
    public void onTabChanged(String tabId) {
        super.onTabChanged(tabId);
        if (!MORE_TAB_TAG.equals(mLastTab) && !TextUtils.isEmpty(mLastTab)) {
            NewsListFragment f = (NewsListFragment) getTabManager().getTabInfos().get(mLastTab)
                    .getFragment();
            f.detachLoadingListView();
        }

        mLastTab = tabId;
        
		if (!MORE_TAB_TAG.equals(tabId)) {
			mLoadingListView.setVisibility(View.VISIBLE);
			NewsListFragment f = (NewsListFragment) getTabManager().getTabInfos().get(tabId)
                    .getFragment();
			f.attachLoadingListView(mLoadingListView);
		} else {
			mLoadingListView.setVisibility(View.GONE);
		}
    }

    @Override
    public boolean onMenuOpen() {
        ViewGroup menu = (ViewGroup) getMenuView().findViewById(R.id.menu_theme_change);
        TextView title = (TextView) menu.getChildAt(1);
        ImageView image = (ImageView) menu.getChildAt(0);
        if (getThemeSettingsHelper().isNightTheme(getActivity())) {
            title.setText(R.string.theme_default);
            image.setImageResource(R.drawable.ic_menu_theme_default);
        } else {
            title.setText(R.string.theme_night);
            image.setImageResource(R.drawable.ic_menu_theme_night);
        }

        menu = (ViewGroup) getMenuView().findViewById(R.id.menu_download_article);
        title = (TextView) menu.getChildAt(1);
        image = (ImageView) menu.getChildAt(0);
        MyApplication app = getApplication();
        if (!app.getIsDownOffline()) {
            title.setText("离线下载");
        } else {
            title.setText("取消下载");
        }

        return super.onMenuOpen();
    }

    @Override
    public void onMenuClick(int id) {
        switch (id) {
            case R.id.menu_download_article: {
               
                break;
            }
            case R.id.menu_theme_change: {
                ((HomePage) getActivity()).changeTheme();
                break;
            }
            case R.id.menu_news_search: {
                Intent intent = new Intent(getActivity(), SearchNewsActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.menu_my_comment: {
                ((HomePage) getActivity()).goToMyComment();
                break;
            }
            case R.id.menu_my_collect: {
                ((HomePage) getActivity()).goToMyCollect();
                break;
            }
            case R.id.menu_make_column: {
               
                break;
            }
            case R.id.menu_setting: {
                ((HomePage) getActivity()).goToSetting();
                break;
            }
            case R.id.menu_exit: {
                ((HomePage) getActivity()).showExit();
                break;
            }
            default:
                break;
        }
    }

    public List<Map<String, Object>> getColumnList() {
        return mColumnsList;
    }

    @Override
    protected void initTabhost(TabManager tabManager, TabHost tabHost) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        MyTabWidget tabWidget = (MyTabWidget) tabHost.getTabWidget();
        View animationView = inflater.inflate(R.layout.comment_tab_indicator_bg, null);
        View bg = animationView.findViewById(R.id.indicator_bg);
        bg.setBackgroundResource(R.drawable.slidebar);
        tabWidget.setAnimaitonView(animationView);

        final Context context = getActivity();
        final SQLiteDatabase db = getDb();
        List<Map<String, Object>> columnsListData = NewsColumn.getColumnListFromDB(context,
                db);
        if (columnsListData == null || columnsListData.size() == 0) {
            columnsListData = NewsColumn.getDefaultColumnList(context, db);
        }
        updateTab(tabManager, tabHost, inflater, columnsListData);
        
        if (Tools.CheckNetwork(context) && StringUtil.isNeedRefresh(context, "column_list")) {
            new Thread() {
                @Override
                public void run() {
                    NewsColumn.getColumnListFromNet(context, db);
                }
                
            }.start();
        }
    }

    /**
     * 更新栏目tab
     * 
     * @param tabManager
     * @param tabHost
     * @param inflater
     */
    private void updateTab(TabManager tabManager, TabHost tabHost, LayoutInflater inflater) {
        List<Map<String, Object>> columnsListData = NewsColumn.getColumnListFromDB(getActivity(),
                getDb());
        updateTab(tabManager, tabHost, inflater, columnsListData);
    }

    /**
     * 更新栏目tab
     * 
     * @param tabManager
     * @param tabHost
     * @param inflater
     * @param columnsListData
     */
    private void updateTab(TabManager tabManager, TabHost tabHost, LayoutInflater inflater,
            List<Map<String, Object>> columnsListData) {

        // 保留已经存在栏目
        HashMap<String, TabInfo> tabInfos = new HashMap<String, TabInfo>();
        tabInfos.putAll(tabManager.getTabInfos());
        
        boolean needApplyTheme = tabInfos.size() > 0;
        
        mColumnsList.clear();
        if (columnsListData == null || columnsListData.size() == 0) {
            clearTabs();
            removeFragmemts(tabInfos);
            return;
        }

        mColumnsList.addAll(columnsListData);

        clearTabs();
        detachFragmemts(tabInfos);

        final int count = columnsListData.size();

        // 以下20要和布局文件中HorizontalScrollView的左右padding的和保持一致
        int width = ((int) (getResources().getDisplayMetrics().widthPixels - getResources()
                .getDisplayMetrics().density * 20) / 6);

        for (int i = 0; i < count; i++) {
            Map<String, Object> item = columnsListData.get(i);

            String columnID = (String) ModelUtils.getValue(item, GetColumnsInfo.TID_TAG);
            String columnName = (String) ModelUtils.getValue(item, GetColumnsInfo.TNAME_TAG);
            String columnUrl = (String) ModelUtils.getValue(item, GetColumnsInfo.TID_TAG);

            // 如果是已经存在栏目,直接使用,否则添加新栏目
            TabInfo info = tabInfos.remove(columnID);
            if (info == null) {
                Bundle bundle = new Bundle();
                bundle.putString(NewsListFragment.COLUMN_NAME, columnName);
                bundle.putString(NewsListFragment.COLUMN_ID, columnID);
                bundle.putString(NewsListFragment.COLUMN_URL, columnUrl);

                if (i == 0) {
                    addSpec(tabManager, tabHost, columnID, columnName,
                            NewsListWithHeadlineFragment.class, inflater, bundle, width);
                } else {
                    addSpec(tabManager, tabHost, columnID, columnName, NewsListFragment.class,
                            inflater, bundle, width);
                }
            } else {
                addSpec(tabManager, tabHost, columnID, columnName, info, inflater, width);
            }
        }

        TabInfo info = tabInfos.remove(MORE_TAB_TAG);
        if (info == null) {
            addSpec(tabManager, tabHost, MORE_TAB_TAG, "更多", NewsMoreListFragment.class, inflater, null,
                    width);
        } else {
            if (info.getFragment() != null) {
                ((NewsMoreListFragment) info.getFragment()).updateData();
            }
            addSpec(tabManager, tabHost, MORE_TAB_TAG, "更多", info, inflater, width);
        }

        // 如果原来已经存在的，说明这次更新需要更新主题 
        if (needApplyTheme) {
            applyThemeForTabWidget(getActivity(), getThemeSettingsHelper(), tabHost,
                    (MyTabWidget) tabHost.getTabWidget());
        }
        
        // 清空其它fragment
        removeFragmemts(tabInfos);
        
        // 开始启动离线下载
        addAutoDownloadFragment();
    }

    private void addSpec(TabManager tabManager, TabHost tabHost, String tag, String title,
            Class clazz, LayoutInflater inflater, Bundle bundle, int width) {
        TabSpec spec = tabHost.newTabSpec(tag);
        View view = inflater.inflate(R.layout.comment_tab_indicator, null);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        TextView tabIndicator = (TextView) view.findViewById(R.id.comment_tab_indicator);
        tabIndicator.setText(title);
        spec.setIndicator(view);

        TabInfo info = new TabInfo(tag, clazz, bundle, MORE_TAB_TAG.equals(tag));
        
        tabManager.addTab(spec, info);
    }

    private void addSpec(TabManager tabManager, TabHost tabHost, String tag, String title,
            TabInfo info, LayoutInflater inflater, int width) {
        TabSpec spec = tabHost.newTabSpec(tag);
        View view = inflater.inflate(R.layout.comment_tab_indicator, null);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        TextView tabIndicator = (TextView) view.findViewById(R.id.comment_tab_indicator);
        tabIndicator.setText(title);
        spec.setIndicator(view);

        tabManager.addTab(spec, info);
    }

	private void removeFragmemts(HashMap<String, TabInfo> tabInfos) {
		if (tabInfos != null && tabInfos.size() > 0) {
			FragmentManager fm = getFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();

			Iterator<String> iterator = tabInfos.keySet().iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				NRFragment fragment = (NRFragment) (tabInfos.get(key)
						.getFragment());
				if (fragment != null) {
					ft.remove(fragment);
				}
			}
			FragmentUtil.commitAndExec(fm, ft, false);
		}
	}
	private void detachFragmemts(HashMap<String, TabInfo> tabInfos) {
		if (tabInfos != null && tabInfos.size() > 0) {
			FragmentManager fm = getFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();

			Iterator<String> iterator = tabInfos.keySet().iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				NRFragment fragment = (NRFragment) (tabInfos.get(key)
						.getFragment());
				if (fragment != null) {
					ft.detach(fragment);
				}
			}
			FragmentUtil.commitAndExec(fm, ft, false);
		}
	} 

    /**
     * 增加离线下载fragment
     */
    private void addAutoDownloadFragment() {}

    @Override
    public void onApplyTheme() {
        super.onApplyTheme();

        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Activity context = getActivity();

        TabHost tabHost = getTabHost();
        MyTabWidget tabWidget = (MyTabWidget) tabHost.getTabWidget();
        
        applyThemeForTabWidget(context, themeSettingsHelper, tabHost, tabWidget);
        
        themeSettingsHelper.setListViewDivider(context, mLoadingListView.getListView(),
                R.drawable.list_divider_line);

        Button moreButton = (Button) mLoadingListView.getLoadingMoreClickView();
		if (moreButton != null) {
			themeSettingsHelper.setViewBackgroud(context, moreButton,
					R.drawable.netease_big_button);
			themeSettingsHelper.setTextViewColor(context, moreButton,
					R.color.list_title_color);
		}
        
        // 菜单夜间模式
        View menuView = getMenuView();
        themeSettingsHelper.setViewBackgroudColor(context, menuView
                .findViewById(R.id.menu_tabrow_1), R.color.menu_layout_bg_color);
        themeSettingsHelper.setViewBackgroudColor(context, menuView
                .findViewById(R.id.menu_tabrow_2), R.color.menu_layout_bg_color);
        
        LinearLayout menuItem = (LinearLayout) menuView.findViewById(R.id.menu_download_article);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, true);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_theme_change);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, true);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_news_search);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, true);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_my_comment);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, true);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_my_collect);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, false);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_make_column);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, false);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_setting);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, false);
        menuItem = (LinearLayout) menuView.findViewById(R.id.menu_exit);
        applyThemeForMenu(context, themeSettingsHelper, menuItem, false);
    }

    private void applyThemeForMenu(Context context, ThemeSettingsHelper themeSettingsHelper,
            LinearLayout menuView, boolean isUp) {
        themeSettingsHelper.setViewBackgroud(context, menuView, isUp ? R.drawable.menu_background
                : R.drawable.menu_background_below);
        themeSettingsHelper.setTextViewColor(context, (TextView) menuView.getChildAt(1),
                R.color.menu_text_color);

    }
    
    private void applyThemeForTabWidget(Context context, ThemeSettingsHelper themeSettingsHelper,
            TabHost tabHost, MyTabWidget tabWidget) {

        View scrollTabs = tabHost.findViewById(R.id.scroll_tabs);
        themeSettingsHelper.setViewBackgroud(context, scrollTabs, R.drawable.top_column_bg);

        View indicatorBgView = tabWidget.getAnimationView().findViewById(R.id.indicator_bg);
        themeSettingsHelper.setViewBackgroud(context, indicatorBgView, R.drawable.slidebar);
        final int count = tabWidget.getTabCount();
        for (int i = 0; i < count; i++) {
            TextView t = (TextView) tabWidget.getChildTabViewAt(i).findViewById(
                    R.id.comment_tab_indicator);
            themeSettingsHelper.setTextViewColor(context, t, R.color.column_item_color);
        }
    }
}
